import {
  CallHandler,
  ExecutionContext,
  Injectable,
  NestInterceptor,
} from '@nestjs/common';
import { Request } from 'express';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

export interface ResponseFormat<T> {
  success: boolean;
  message: string;
  data: T;
}

@Injectable()
export class TransformInterceptor<T>
  implements NestInterceptor<T, ResponseFormat<T>>
{
  intercept(
    context: ExecutionContext,
    next: CallHandler,
  ): Observable<ResponseFormat<T>> {
    // 获取请求信息，用于自定义消息
    const httpContext = context.switchToHttp();
    const request = httpContext.getRequest<Request>();
    const method = request.method;

    // 根据请求方法生成适当的消息
    let message = '操作成功';
    if (method === 'GET') {
      message = '查询成功';
    } else if (method === 'POST') {
      message = '创建成功';
    } else if (method === 'PUT' || method === 'PATCH') {
      message = '更新成功';
    } else if (method === 'DELETE') {
      message = '删除成功';
    }

    return next.handle().pipe(
      map(
        (data: T): ResponseFormat<T> => ({
          success: true,
          message,
          data,
        }),
      ),
    );
  }
}
